<?php
/**
 * Grade.php
 * Notes:分支机构等级
 * author: chen
 * DateTime: 2022/6/15 9:23
 * @package Xtsb\Cims\Branch
 */

namespace Xtsb\Cims\Branch;

use app\Http\OA\Servers\BranchApplyServer;
use think\facade\Db;

class Branch
{
  //是否配置仅显示本级机构和上级机构人员信息
  public static function showMyBranch()
  {
    $showMyBranch = Db::name('configuration')
      ->where('cuid', CUID)->where('code', 'staff')->value('content');
    if ($showMyBranch == 1) {
      return true;
    }
    //随时撤回
    return false;
  }

  /**
   * 根据当前机构， 获取所有的本机构+下级机构id, 由于需要做数据隔离
   * @param bool $is_string 是否返回字符串
   * @param int $count 向下读取次数， 填写1，仅读取直属分支机构，最多读取10级
   * @param int $branch_id 指定某个分支机构，进行向下读取
   * @param bool $exclude 返回列表是否包含指定机构，默认包含
   * @param bool $is_check_status 是否校验status 默认校验
   * @return array
   */
  public static function getAllSubBranch($is_string = false, $count = 10, $branch_id = null, $exclude = false, $is_check_status = true)
  {
    $where[] = ['cuid', '=', CUID];

    if ($is_check_status) {
      $where[] = ['status', '=', 1];
    }

    if (!$branch_id && (is_ceo() || (BRANCHNAME == '总部' && is_admin_department()))) {
      $list = Db::name('branch')->where($where)->column('id');
    } else {
      if (is_admin_department()) {
        empty($branch_id) and $branch_id = BRANCHID;
        if (is_array($branch_id)) {
          $list = $branch_id;
          $check_list = $branch_id;
        }else{
          $list = [$branch_id];
          $check_list = [$branch_id];
        }

        $i = 0;
        while (true) {
          $check_list = Db::name('branch')->where($where)->whereIn('pid', $check_list)->column('id');
          if ($check_list) {
            $list = array_merge($list, $check_list);
            $i++;
            if ($i == $count)
              break;
          } else {
            break;
          }
        }
        if ($exclude) {
          unset($list[0]);
        }
      } else {
        $list = self::getUpBranch(false, 0);
      }
    }
    if ($is_string)
      return '(' . implode(',', $list) . ')';
    else
      return $list;

  }


  /**
   * 根据当前机构，获取上级id
   * @param bool $is_string 是否返回字符串
   * @param int $count 向上读取次数，填写1，仅获取直接上级机构，最多读取10级
   * @return array
   */
  public static function getUpBranch($is_string = false, $count = 10, $branch_id = null)
  {
    if (!empty(BRANCHID) || !empty($branch_id)) {
      $list = [$branch_id ?? BRANCHID];
    }

    if (BRANCHNAME != '总部' && $count > 0) {
      $branch_id = $branch_id ?? BRANCHID;
      $i = 0;
      while (true) {
        $branch_id = Db::name('branch')->where('cuid', CUID)->where('id', $branch_id)->value('pid');
        if ($branch_id) {
          //存在上级，填写上级id，并继续循环
          $list[] = $branch_id;
          $i++;
          if ($i == $count)
            break;
        } else {
          //不存在上级，填写总部id， 并中断循环
          $list[] = Db::name('branch')->where('cuid', CUID)->where('title', '总部')->value('id');
          break;
        }
      }
    }
    foreach ($list as $k=>$v){
      if(!$v){
        unset($list[$k]);
      }
    }
    if ($is_string)
      return '(' . implode(',', $list) . ')';
    else
      return $list;
  }

  /**
   * 根据当前机构，获取本机构+所有下级机构的部门id
   * @param bool $is_string 是否返回字符串
   * @param int $count 向下读取次数，为1时读取直属分支机构的部门，最多读取10级
   * @return array
   */
  public static function getAllSubDm($is_string = false, $count = 10, $branch_id = null)
  {
    //企业管理员，或者职能部门的行政岗位，可以向下获取本机构下的所有部门信息
    if (!$branch_id && (is_ceo() || (is_admin_department() && is_manager()))) {
      $branch_list = self::getAllSubBranch(false, $count);
      $list = DB::name('dm')->where('cuid', CUID)->whereIn('branch_id', $branch_list)->column('id');
    } //否则只能获取本部门
    else {
      $list = [DMID];
      if (is_admin_department()) {
        empty($branch_id) and $branch_id = BRANCHID;
        $check_list = is_array($branch_id)?$branch_id:[$branch_id];

        $i = 0;
        while (true) {
          $dm_list = Db::name('dm')->whereIn('branch_id', $check_list)->column('id');
          if ($dm_list)
            $list = array_merge($list, $dm_list);
          $i++;
          if ($i == $count)
            break;

          $check_list = Db::name('branch')->where('cuid', CUID)->whereIn('pid', $check_list)->column('id');
          if (!$check_list)
            break;
        }
      }
    }
    if ($is_string)
      return '(' . implode(',', $list) . ')';
    else
      return $list;
  }

  public static function getAllSubDmList()
  {
    return Db::name('dm')->alias('d')
      ->field('d.id value,  CONCAT(IFNULL(b.title,"无机构"),">",IFNULL(d.title,"无部门")) label, d.branch_id')
      ->leftJoin('branch b', 'b.id = d.branch_id')
      ->whereIn('d.id', self::getAllSubDm())->select();
  }

  public static function getAllSubBranchList()
  {
    return Db::name('branch')->field('id value, title label')
      ->whereIn('id', self::getAllSubBranch())->select();
  }

  //判断当前账号是否可以选择到对应的分支机构
  public static function checkBranchSupervisor(&$branch_id)
  {
    $branch_id = (int)$branch_id;
    if (!empty($branch_id)) {

      if (is_ceo() || (is_admin_department() && is_manager())) {

      } else {
        $branch_id_arr = self::getAllSubBranch();
        if (!in_array((int)$branch_id, $branch_id_arr))
          $branch_id = null;
      }
    } else {
      $branch_id = null;
    }
  }

  //判断当前账号是否可以选择到对应的部门
  public static function checkDmSupervisor(&$dm_id)
  {
    $dm_id = (int)$dm_id;
    if (!empty($dm_id)) {

      if (is_ceo() || (is_admin_department() && is_manager())) {

      } else {
        $dm_id_arr = self::getAllSubDm();
        if (!in_array((int)$dm_id, $dm_id_arr))
          $dm_id = null;
      }
    } else {
      $dm_id = null;
    }

  }

  /**
   * 自动构造对应的branch_id， dm_id, 适用于各种统计和检索条件的构造
   * @param null $branch_id 可指定机构，若为空， 系统自动构造，并检查是否对该机构具备权限
   * @param null $dm_id 可指定部门，若为空， 系统自动构造，并检查是否对该机构具备权限
   * @param bool $strict 项目部门， 是否可查询本机构下的其他人员，默认不可查询，
   */
  public static function checkBranchDmSupervisor(&$branch_id, &$dm_id, $strict = true)
  {

    //校验是否有对应机构的权限
    Branch::checkBranchSupervisor($branch_id);
    Branch::checkBranchSupervisor($dm_id);

    if (empty($branch_id) && is_branch())
      $branch_id = BRANCHID;

    if (!is_admin_department() && !$strict)
      $dm_id = DMID;
  }

  /**
   * 获取主管/经理的管理部门
   * @return array
   */
  public static function getManageDm()
  {
    return Db::name('dm')->where('cuid', CUID)->where('manager_id|leader_id', UID)->column('id');
  }

  /**
   *仅限于列表数据查询
   * 数据权限： 1: 全公司通用 2:仅限机构内部 3:本机构及下属所有机构通用 4:部门专属
   * @param null $prefix
   * @param bool $include_creator 是否要读取本人创建的数据，true:一般在列表显示 false：在数据引用模块显示
   * @return string
   */
  public static function getWhereDataPrivilege($prefix = null, $include_creator = false, $is_index = true)
  {

    if (is_ceo())
      return '';

    $prefix = isset($prefix) ? $prefix . '.' : '';

    if ($include_creator)
      $whereOr[] = $prefix . 'creator=' . UID;
    $data_privilege = input('data_privilege');
    //公司通用
    if (!$data_privilege || $data_privilege == 1) {
      $whereOr[] = $prefix . 'data_privilege=1';
    }
    //仅限机构内部使用
    if (!$data_privilege || $data_privilege == 2) {
      $whereOr[] = '(' . $prefix . 'branch_id =' . BRANCHID . ' and ' . $prefix . 'data_privilege=2)';
    }
    //上级机构提供的数据
    if (!$data_privilege || $data_privilege == 3) {
      $branch_list = self::getUpBranch(true);
      $whereOr[] = '(' . $prefix . 'branch_id in ' . $branch_list . ' and ' . $prefix . 'data_privilege=3)';
    }
    //仅限部门的数据， 上游可以往下查询和修改
    if (!$data_privilege || $data_privilege == 4) {
      if (!$is_index) {
        $dm_list = '(' . DMID . ')';
      } else {
        $dm_list = self::getAllSubDm(true);
      }

      $whereOr[] = '(' . $prefix . 'dm_id in ' . $dm_list . ' and ' . $prefix . 'data_privilege=4)';
    }
    return '(' . implode(' or ', $whereOr) . ')';
  }


  //更新项目费用的归属信息，以及业务预览信息
  public static function updateProjectCost($table_name, $table_id, $change_dm = true, $change_field = [])
  {
    $info = Db::name($table_name)->where('id', $table_id)->field('cuid, branch_id, dm_id, dm_id applyer_dm_id')->find();
    if (!$info)
      return;
    $where[] = ['g.cuid', '=', $info['cuid']];
    $where[] = ['g.' . $table_name . '_id', '=', $table_id];
    $where_dm = $where;
    switch ($table_name) {
      case 'sale_lead':
        if (in_array('title', $change_field))
          $change_field = true;
        else
          $change_field = false;
        break;
      case 'bid':
        break;
      case 'cca':
        $where_dm[] = ['g.cor_id', '=', null];
        if (in_array('title', $change_field) || in_array('order_no', $change_field))
          $change_field = true;
        else
          $change_field = false;
        break;
      case 'cor':
        $where_dm[] = ['g.project_ledger_id', '=', null];
        if (in_array('title', $change_field) || in_array('cor_no', $change_field))
          $change_field = true;
        else
          $change_field = false;
        break;
      case 'project_ledger':
        if (in_array('title', $change_field) || in_array('order_no', $change_field))
          $change_field = true;
        else
          $change_field = false;
        break;
      default:
        $where = [];
        break;
    }
    if (empty($where))
      return;

    if ($change_dm) {
      Db::name('cost_apply')->alias('g')->where($where_dm)->update($info);

      $where_dm[] = ['g.table_name', 'in', ['my_cost', 'team_borrow', 'my_imprest']];
      Db::name('cost_overview')->alias('g')->where($where_dm)->update($info);
    }

    if ($change_dm || $change_field) {
      $where[] = ['a.table_name', 'in', ['my_cost', 'team_borrow', 'my_imprest']];
      $cost_arr = Db::name('cost_apply')->alias('g')
        ->field('a.table_name, a.table_id')
        ->leftJoin('apm_item a', 'a.table_id = g.id')
        ->where($where)->select()->toArray();
      if ($cost_arr) {
        foreach ($cost_arr as $item) {
          \app\Http\OA\Servers\ApmServer::setApmItemContent($item['table_name'], $item['table_id']);
        }
      }
    }


  }

  //更新项目其他费用的业务预览信息，例如： 采购、工程队结算、工资发放、下游结算
  public static function updateProjectOtherCost($table_name, $table_id, $change_field = true)
  {
    switch ($table_name) {
      case 'cca':
        $where[] = ['g.cca_id', '=', $table_id];
        if (in_array('title', $change_field) || in_array('order_no', $change_field))
          $change_field = true;
        else
          $change_field = false;
        break;
      case 'cor':
        $where[] = ['g.cor_id', '=', $table_id];
        if (in_array('title', $change_field) || in_array('cor_no', $change_field))
          $change_field = true;
        else
          $change_field = false;
        break;
      default:
        $where = [];
        break;
    }

    if (empty($where))
      return;
    if ($change_field) {
      $where[] = ['g.table_name', 'in', ['team_salary', 'team_settlement_pay', 'goods_purchase_pay', 'finance_settlement']];
      $cost_arr = Db::name('cost_overview')->alias('g')->field('g.table_name, g.table_id')->where($where)->select()->toArray();

      if ($cost_arr) {
        foreach ($cost_arr as $item) {
          \app\Http\OA\Servers\ApmServer::setApmItemContent($item['table_name'], $item['table_id']);
        }
      }
    }


  }

  //更新项目任务的项目名称
  public static function updateProjectTask($table_name, $table_id, $change_field = [], $title = null)
  {

    if (!in_array('title', $change_field))
      return;
    Db::name('project_task')->where('table_name', $table_name)->where('table_id', $table_id)
      ->update(['project_name' => $title]);

  }

  //获取id 对应的上级机构label
  public static function label($branchId)
  {
    $branchName = '';
    while ($branchId > 0) {
      $info = Db::name('branch')->field('id,pid,title')->where('id', $branchId)->find();
      $branchId = $info['pid'] ?? 0;
      if (isset($info['title']) && $info['title']) {
        $branchName = $info['title'] . ' / ' . $branchName;
      }
    }

    return substr($branchName, 0, -2);
  }

  /**
   * 获取 $currentBranchId 父级id
   * @param $currentDmId
   * @return array
   */
  public static function parentIds($currentBranchId)
  {
    $parentIds[] = $currentBranchId;//包含当前id
    while ($currentBranchId > 0) {
      $currentBranchId = Db::name('branch')->where('id', $currentBranchId)->value('pid');
      if ($currentBranchId) {
        $parentIds[] = $currentBranchId;
      }

    }

    return $parentIds;
  }

  /**
   * Notes:返回后代机构id
   * author: chen
   * DateTime: 2023/2/17 15:14
   */
  public static function childs($branchId, &$childs , $isSort = false)
  {
//    if (!is_branch()) {
//      $childs = Db::name('branch')
//        ->where('cuid', CUID)
//        ->column('id');
//    } else {
//      $childs[] = $branchId;
//      $branchIds = Db::name('branch')
//        ->where('cuid', CUID)
//        ->where('pid', $branchId)->column('id');
//      foreach ($branchIds as $branchId) {
//        self::childs($branchId, $childs);
//      }
//    }
    $orderBy = "";
    if($isSort){
      $orderBy = "sort ASC";
    }
    $childs[] = $branchId;
    $branchIds = Db::name('branch')
      ->where('cuid', CUID)
      ->where('pid', $branchId)
      ->order($orderBy)
      ->column('id');
    foreach ($branchIds as $branchId) {
      self::childs($branchId, $childs,$isSort);
    }

  }

}
